import time
import ctypes
from datetime import datetime, timedelta
import schedule
import threading

# 弹窗提醒函数
def show_reminder(message="今天有早八，别迟到"):
    # 使用Windows的消息框
    ctypes.windll.user32.MessageBoxW(0, message, "上课提醒", 0x40 | 0x0)
    print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 已显示提醒: {message}")

# 设置定时任务
def set_reminder(hour=7, minute=30, message="今天有早八，别迟到"):
    schedule.every().day.at(f"{hour:02d}:{minute:02d}").do(show_reminder, message)
    print(f"已设置每天 {hour:02d}:{minute:02d} 的提醒: {message}")

# 立即测试提醒
def test_reminder(message="今天有早八，别迟到"):
    confirm = input("是否立即测试提醒功能？(y/n): ")
    if confirm.lower() == 'y':
        show_reminder(message)

# 运行调度器
def run_scheduler():
    while True:
        schedule.run_pending()
        time.sleep(1)

# 主函数
def main():
    print("=== 上课提醒脚本 ===")
    
    # 设置默认提醒
    default_hour = 7
    default_minute = 30
    default_message = "今天有早八，别迟到"
    
    # 询问用户是否要自定义提醒
    customize = input(f"是否自定义提醒时间和内容？(默认: 每天 {default_hour:02d}:{default_minute:02d}, 消息: '{default_message}') (y/n): ")
    
    if customize.lower() == 'y':
        try:
            custom_hour = int(input("请输入小时 (0-23): "))
            custom_minute = int(input("请输入分钟 (0-59): "))
            custom_message = input("请输入提醒消息: ")
            
            if 0 <= custom_hour <= 23 and 0 <= custom_minute <= 59:
                set_reminder(custom_hour, custom_minute, custom_message)
            else:
                print("时间输入无效，使用默认设置")
                set_reminder(default_hour, default_minute, default_message)
        except ValueError:
            print("输入格式错误，使用默认设置")
            set_reminder(default_hour, default_minute, default_message)
    else:
        set_reminder(default_hour, default_minute, default_message)
    
    # 测试提醒
    test_reminder()
    
    # 开始后台运行
    print("\n提醒脚本已启动，将在后台持续运行")
    print("按 Ctrl+C 停止脚本")
    
    # 创建并启动调度线程
    scheduler_thread = threading.Thread(target=run_scheduler, daemon=True)
    scheduler_thread.start()
    
    # 主线程保持运行
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("\n脚本已停止")

if __name__ == "__main__":
    # 检查并安装必要的依赖
    try:
        import schedule
    except ImportError:
        print("正在安装必要的依赖包...")
        import subprocess
        subprocess.check_call(["python", "-m", "pip", "install", "schedule"])
        print("依赖包安装完成")
        import schedule
    
    main()